/**
 * @typedef {object} choiceConfig
 *
 * @property {string} name choice title
 * @property {string} value choice value
 * @property {string} description choice description
 */

/**
 * @typedef {object} optionConfig
 *
 * @property {string} name unique question name
 * @property {string=} description question description
 * @property {'list' | 'input'} type question type
 * @property {string} message question tips
 * @property {choiceConfig[]=} choices question choices
 * @property {string | number} default default answer
 * @property {boolean} required question is required
 * @property {string=} when optional question condition
 */

/**
 * @param {optionConfig} config
 */
function createOption(config) {
  const option = {};
  const optional = !config.required ? ' (Optional)' : '';
  option.name = config.name;
  option.type = config.type;
  option.message = config.message + optional;
  if (config.description) {
    option.suffix = config.description + '\n';
  }
  if (config.type === "list") {
    const maxLength = Math.max(...config.choices.map(c => c.name.length));
    option.choices = config.choices.map(c => {
      const desc = c.description ? ' : ' + c.description : '';
      return {
        name: c.name.padEnd(maxLength, ' ') + desc,
        value: c.value
      }
    });
  }
  if (config.type === 'input') {
    option.message += '\n';
  }
  if (config.default) {
    option.default = config.default;
  }
  if (config.description) {
    option.description = config.description;
  }
  if (config.when) {
    const [questionName, questionAnswer] = config.when.split('#');
    option.when = answer => answer[questionName] === questionAnswer;
  }
  return option;
}

/**
 * create question
 * @param {optionConfig[]} configList config list
 */
function createQuestions(configList) {
  const questions = configList.map(config => createOption(config));

  return questions;
}

module.exports = createQuestions;
